import requests
import json
from flask import Flask, request

app = Flask(__name__)
# 获取access_token和refresh_token
with open('get_token', 'r') as init_f:
    access_token = init_f.readline()[0:-1]
    refresh_token = init_f.readline()[0:-1]
    init_f.close()
redirect_uri = 'http://localhost:5000/callback'
client_id = 'b9347f605ab057d98e099241bf76bb67fca9a19f70af01e40e5dc4312fe1105c'
client_secret = 'c0fb7e886254903d4eeb032f237537c97ffff9a5ac0f43148dba9aec3c91b22e'
host = 'https://gitee.com/oauth/'
endpoint = ['authorize', 'token']
grant_type = ['authorization_code', 'refresh_token']
limits = [
    'user_info',
    'projects',
    'pull_requests',
    'issues',
    'notes',
    'keys',
    'hook',
    'groups',
    'gists',
    'enterprises',
    'emails'
]
# 添加权限
limits_str = ''
for limit in limits:
    limits_str += limit
    if limit != limits[-1]:
        limits_str += '%20'
# 获取code的参数字典
data_get_code = {
    'client_id': client_id,
    'redirect_uri': redirect_uri,
    'response_type': 'code',
    'scope': limits_str
}
# 获取access_token的参数字典
data_get_access_token = {
    'grant_type': grant_type[0],
    'code': '',
    'client_id': client_id,
    'redirect_uri': redirect_uri,
    'client_secret': client_secret
}
# 刷新access_token的参数字典
data_refresh = {
    'grant_type': grant_type[1],
    'refresh_token': refresh_token
}

# 授权码字串
# endpoint[0] + data_get_code为获取code
# endpoint[1] + data_get_access_token为获取令牌
# endpoint[1] + data_refresh为刷新令牌

# 初始化令牌，第一次需要手动获取code从而获取令牌，之后就可以用refresh_token来刷新令牌了，因为refresh_token过期时间远大于access_token，且刷新步骤可自动执行
# 步骤：开启init()然后将code_url粘到浏览器中即可
code_url = 'https://gitee.com/oauth/authorize?client_id=b9347f605ab057d98e099241bf76bb67fca9a19f70af01e40e5dc4312fe1105c&redirect_uri=http://localhost:5000/callback&response_type=code&scope=user_info%20projects%20pull_requests%20issues%20notes%20keys%20hook%20groups%20gists%20enterprises%20emails'
# 获取access_token的网址
token_url = ''.join([host, endpoint[1]])


# 本地使用Flask手动获取access_token和refresh_token初值
@app.route('/callback', methods=['POST', 'GET'])
def callback():
    global access_token, refresh_token
    if request.args.get('code'):
        data_get_access_token['code'] = request.args.get('code')
        r = requests.post(token_url, params=data_get_access_token)
        r = json.loads(r.text)
        with open('get_token', 'w') as f:
            f.writelines(r['access_token'] + '\n')
            f.writelines(r['refresh_token'] + '\n')
            f.close()
        return 'successful'


# 开启flask，可以从/callback处接收code，从而刷新token
def init():
    app.run()


# 刷新access_token的接口
def refresh_access_token():
    global access_token, refresh_token
    r = requests.post(token_url, params=data_refresh)
    r = json.loads(r.text)
    with open('get_token', 'w') as f:
        f.writelines(r['access_token'] + '\n')
        f.writelines(r['refresh_token'] + '\n')
        f.close()


refresh_access_token()
